import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:material_dialogs/dialogs.dart';
import 'package:material_dialogs/shared/types.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/options_item.dart';
import 'package:tracker/pages/home/setting/dialog/command_dialog_interface.dart';
import 'package:tracker/theme/app_theme.dart';

const _hour = 60 * 60;

/// 工作模式弹窗
class WorkModeDialog implements CommandDialogInterface {
  final GlobalKey<ScaffoldState> scaffoldKey;
  final String? cmdCode;
  late StateSetter _newSetState;

  // 回调函数
  final Function(String cmdContent)? onConfirm;

  WorkModeDialog({
    required this.scaffoldKey,
    required this.cmdCode,
    this.onConfirm,
  });

  // 模式
  int switchValue = 0;

  // 默认改成30秒
  int modeOptionsIndex1 = 0;

  final modeOptions1 = [
    // 干掉10秒的选项
    // OptionsItem(label: '10秒', value: 10),
    OptionsItem(label: '30秒', value: 30),
    OptionsItem(label: '3分', value: 3 * 60),
    OptionsItem(label: '5分', value: 5 * 60),
  ];

  int modeOptionsIndex2 = 0;

  final modeOptions2 = [
    OptionsItem(label: '1小时', value: 1 * _hour),
    OptionsItem(label: '2小时', value: 2 * _hour),
    OptionsItem(label: '6小时', value: 6 * _hour),
    OptionsItem(label: '12小时', value: 12 * _hour),
    OptionsItem(label: '24小时', value: 24 * _hour),
  ];

  @override
  void show(BuildContext context) {
    return Dialogs.bottomMaterialDialog(
        context: context,
        isScrollControlled: true,
        customView: StatefulBuilder(builder: (newContext, newSetState) {
          _newSetState = newSetState;
          return Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.white,
                  Colors.grey.shade50,
                ],
              ),
              borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(10),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [
                            AppTheme.themeConfig.primaryColor.withOpacity(0.15),
                            AppTheme.themeConfig.primaryColor.withOpacity(0.05),
                          ],
                        ),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.settings_suggest,
                        color: AppTheme.themeConfig.primaryColor,
                        size: 24,
                      ),
                    ),
                    const SizedBox(width: 12),
                    const Text(
                      '工作模式',
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 20),
                // 智能模式卡片
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: switchValue == 0 ? AppTheme.themeConfig.primaryColor.withOpacity(0.05) : Colors.white,
                    borderRadius: BorderRadius.circular(16),
                    border: Border.all(
                      color: switchValue == 0 ? AppTheme.themeConfig.primaryColor : AppTheme.themeConfig.dividerColor,
                      width: switchValue == 0 ? 2 : 1,
                    ),
                    boxShadow: switchValue == 0 ? [
                      BoxShadow(
                        color: AppTheme.themeConfig.primaryColor.withOpacity(0.1),
                        blurRadius: 8,
                        offset: const Offset(0, 2),
                      ),
                    ] : [],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              '智能模式',
                              style: TextStyle(
                                fontSize: 18,
                                color: AppTheme.themeConfig.primaryTextColor,
                                fontWeight: FontWeight.w700,
                              ),
                            ),
                          ),
                          Radio(
                            value: 0,
                            groupValue: switchValue,
                            onChanged: (value) {
                              XLogger.info('value: $value');
                              newSetState(() {
                                switchValue = value!;
                              });
                            },
                            activeColor: AppTheme.themeConfig.primaryColor,
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                          color: Colors.orange.shade50,
                          borderRadius: BorderRadius.circular(10),
                          border: Border.all(
                            color: Colors.orange.shade200,
                            width: 1,
                          ),
                        ),
                        child: Row(
                          children: [
                            Icon(
                              Icons.info_outline,
                              color: Colors.orange.shade700,
                              size: 16,
                            ),
                            const SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                '根据定位间隔更新定位，间隔越长越省电，间隔越短历史轨迹精确度越高。',
                                style: TextStyle(
                                  fontSize: 13,
                                  color: Colors.grey[700],
                                  height: 1.3,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 12),
                      Row(
                        children: [
                          Text(
                            '定位间隔',
                            style: TextStyle(
                              fontSize: 15,
                              color: AppTheme.themeConfig.primaryTextColor,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          const Spacer(),
                          GestureDetector(
                            onTap: () {
                              Picker picker = Picker(
                                adapter: PickerDataAdapter(
                                  data: modeOptions1.map((e) => PickerItem(text: Text(e.label), value: e.value)).toList(),
                                ),
                                changeToFirst: true,
                                cancelText: '取消',
                                confirmText: '确定',
                                cancelTextStyle: const TextStyle(color: Colors.grey, fontSize: 16),
                                textAlign: TextAlign.left,
                                textStyle: const TextStyle(color: Colors.black, fontSize: 18),
                                selectedTextStyle: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 18),
                                columnPadding: const EdgeInsets.all(8.0),
                                onConfirm: (Picker picker, List value) {
                                  XLogger.info('value: ${value}');
                                  XLogger.info('picker.getSelectedValues(): ${picker.getSelectedValues()}');
                                  newSetState(() {
                                    modeOptionsIndex1 = value[0];
                                  });
                                },
                              );
                              picker.selecteds = [modeOptionsIndex1];
                              picker.showModal(context);
                            },
                            child: Container(
                              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
                              decoration: BoxDecoration(
                                gradient: LinearGradient(
                                  colors: [
                                    AppTheme.themeConfig.primaryColor.withOpacity(0.1),
                                    AppTheme.themeConfig.primaryColor.withOpacity(0.05),
                                  ],
                                ),
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Text(
                                    '${modeOptions1[modeOptionsIndex1].label}',
                                    style: TextStyle(
                                      fontSize: 15,
                                      color: AppTheme.themeConfig.primaryColor,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  const SizedBox(width: 4),
                                  Icon(
                                    Icons.keyboard_arrow_down,
                                    color: AppTheme.themeConfig.primaryColor,
                                    size: 18,
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 16),
                // 省电模式卡片
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: switchValue == 1 ? AppTheme.themeConfig.primaryColor.withOpacity(0.05) : Colors.white,
                    borderRadius: BorderRadius.circular(16),
                    border: Border.all(
                      color: switchValue == 1 ? AppTheme.themeConfig.primaryColor : AppTheme.themeConfig.dividerColor,
                      width: switchValue == 1 ? 2 : 1,
                    ),
                    boxShadow: switchValue == 1 ? [
                      BoxShadow(
                        color: AppTheme.themeConfig.primaryColor.withOpacity(0.1),
                        blurRadius: 8,
                        offset: const Offset(0, 2),
                      ),
                    ] : [],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              '省电模式',
                              style: TextStyle(
                                fontSize: 18,
                                color: AppTheme.themeConfig.primaryTextColor,
                                fontWeight: FontWeight.w700,
                              ),
                            ),
                          ),
                          Radio(
                            value: 1,
                            groupValue: switchValue,
                            onChanged: (value) {
                              XLogger.info('value: $value');
                              newSetState(() {
                                switchValue = value!;
                              });
                            },
                            activeColor: AppTheme.themeConfig.primaryColor,
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                          color: Colors.orange.shade50,
                          borderRadius: BorderRadius.circular(10),
                          border: Border.all(
                            color: Colors.orange.shade200,
                            width: 1,
                          ),
                        ),
                        child: Row(
                          children: [
                            Icon(
                              Icons.info_outline,
                              color: Colors.orange.shade700,
                              size: 16,
                            ),
                            const SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                '每1小时自动更新位置，续航时间长，会影响历史轨迹的精确度。',
                                style: TextStyle(
                                  fontSize: 13,
                                  color: Colors.grey[700],
                                  height: 1.3,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 24),
              ],
            ),
          );
        }),
        customViewPosition: CustomViewPosition.BEFORE_TITLE,
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
            },
            style: TextButton.styleFrom(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
            ),
            child: const Text(
              '取消',
              style: TextStyle(color: Colors.grey, fontSize: 16, fontWeight: FontWeight.w600),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 8),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  AppTheme.themeConfig.primaryColor,
                  AppTheme.themeConfig.primaryColor.withOpacity(0.8),
                ],
              ),
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: AppTheme.themeConfig.primaryColor.withOpacity(0.3),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: TextButton(
              onPressed: () {
                // 发送指令
                Navigator.pop(context);
                onConfirm?.call(getCommand());
              },
              style: TextButton.styleFrom(
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                backgroundColor: Colors.transparent,
              ),
              child: const Text(
                '发送指令',
                style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w700),
              ),
            ),
          ),
        ]);
  }

  @override
  String getCommand() {
    // 拼接指令内容
    if (switchValue == 0) {
      // 智能模式
      return '${cmdCode},${switchValue},${modeOptions1[modeOptionsIndex1].value}';
    }
    // 省电模式
    return '${cmdCode},${switchValue},${_hour}';
  }

  @override
  void updateCmdContent(String cmdContent) {
    if (cmdContent.isEmpty) {
      return;
    }
    final cmdContentList = cmdContent.split(',');
    switchValue = int.parse(cmdContentList[1]);
    if (switchValue == 0) {
      // 智能模式
      var index = modeOptions1.indexWhere((element) => element.value == int.parse(cmdContentList[2]));
      if (index == -1) {
        modeOptionsIndex1 = index;
      }
    } else {
      // 省电模式
      var index = modeOptions2.indexWhere((element) => element.value == int.parse(cmdContentList[2]));
      if (index != -1) {
        modeOptionsIndex2 = index;
      }
    }
  }
}
